import 'dart:convert';
import 'dart:io';

import 'package:app_settings/app_settings.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qr_code_app/common/constant/color_config.dart';
import 'package:todo_flutter/todo_flutter.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

class Util {
  // 从文件读取图像并转换为Uint8List
  Uint8List fileToU8(File file) {
    Uint8List bytes = file.readAsBytesSync();
    return bytes;
  }

  // 将Uint8List编码为字符串
  String u8ToString(Uint8List bytes) {
    String encodedString = base64Encode(bytes);
    return encodedString;
  }

  // 从字符串解码回Uint8List
  Uint8List stringToU8(String s) {
    Uint8List decodedBytes = base64Decode(s);
    return decodedBytes;
  }

  Future<File> getFileFromAsset(String assetPath) async {
    // 加载资源文件作为字节流
    ByteData data = await rootBundle.load(assetPath);
    // 将字节流转换为 Uint8List
    Uint8List bytes = data.buffer.asUint8List();

    // 创建临时文件
    String tempPath = (await getTemporaryDirectory()).path;
    File file = File('$tempPath/${assetPath.split('/').last}');

    // 将字节写入临时文件
    await file.writeAsBytes(bytes);

    return file;
  }

  ///选择图片
  Future<File?> selectImg(BuildContext context) async {
    final PermissionState ps = await PhotoManager.requestPermissionExtend();
    if (ps != PermissionState.authorized && ps != PermissionState.limited) {
      final bool result = await showTipDialogV2(
        context,
        message: '需要打开相册权限',
        cancelText: '取消',
        confirmText: '确定',
      );
      if (result) {
        await AppSettings.openAppSettings();
      }
      return null;
    }

    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
        pickerTheme: ThemeData.dark().copyWith(
          primaryColor: Colors.grey[900],
          primaryColorLight: Colors.grey[900],
          primaryColorDark: Colors.grey[900],
          canvasColor: Colors.grey[850],
          scaffoldBackgroundColor: Colors.grey[900],
          cardColor: Colors.grey[900],
          highlightColor: Colors.transparent,
          textSelectionTheme: TextSelectionThemeData(
            cursorColor: defaultThemeColorWeChat,
            selectionColor: defaultThemeColorWeChat.withAlpha(100),
            selectionHandleColor: defaultThemeColorWeChat,
          ),
          indicatorColor: defaultThemeColorWeChat,
          appBarTheme: const AppBarTheme(
            systemOverlayStyle: SystemUiOverlayStyle(
              statusBarBrightness: Brightness.light,
              statusBarIconBrightness: Brightness.dark,
            ),
            elevation: 0,
          ),
          buttonTheme:
              const ButtonThemeData(buttonColor: defaultThemeColorWeChat),
          colorScheme: ColorScheme(
            primary: Colors.grey[900]!,
            secondary: defaultThemeColorWeChat,
            background: Colors.grey[900]!,
            surface: Colors.grey[900]!,
            brightness: Brightness.dark,
            error: const Color(0xffcf6679),
            onPrimary: Colors.black,
            onSecondary: Colors.black,
            onSurface: Colors.white,
            onBackground: Colors.white,
            onError: Colors.black,
          ),
        ),
      ),
    );
    if (result == null) {
      return null;
    }
    final file = await result.first.file;
    return file;
  }

  static Future<bool> showTipDialogV2(
    BuildContext context, {
    required String message,
    String? title,
    String cancelText = 'Cancel',
    String confirmText = 'Confirm',
    bool singleButton = false,
    bool showClose = false,
    bool canceledOutside = true,
    double? confirmWidth,
    TextAlign textAlign = TextAlign.center,
  }) async {
    final result = await showContentDialogV2<Bundle?>(
      context,
      showClose: showClose,
      canceledOutside: canceledOutside,
      content: Column(
        children: [
          SizedBox(height: 32),
          Visibility(
            visible: ObjectUtil.isNotEmpty(title),
            child: Padding(
              padding: EdgeInsets.only(bottom: 12),
              child: CommonText(
                title ?? '',
                color: ColorsConfig.ff161619,
                fontSize: 20,
                lineHeight: 30,
                fontWeight: FontWeight.w500,
                textAlign: TextAlign.center,
              ),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 16, right: 16, bottom: 24),
            child: CommonText(
              message,
              color: ColorsConfig.ff161619,
              fontSize: 13,
              lineHeight: 18,
              textAlign: textAlign,
            ),
          ),
          Padding(
            padding: EdgeInsets.only(left: 38, right: 38, bottom: 20),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Visibility(
                  visible: !singleButton,
                  child: Expanded(
                    child: CommonButton(
                      cancelText,
                      height: 40,
                      fontSize: 14,
                      textColor: ColorsConfig.ff8a919f,
                      color: Colors.white,
                      radius: 100,
                      borderWidth: 1,
                      borderColor: ColorsConfig.ffeceef2,
                      onPressed: () {
                        RouterUtil.instance
                            .build()
                            .withBool('result', false)
                            .pop();
                      },
                    ),
                  ),
                ),
                Visibility(
                  visible: !singleButton,
                  child: SizedBox(width: 12),
                ),
                Expanded(
                  flex: singleButton ? 0 : 1,
                  child: CommonButton(
                    confirmText,
                    width: confirmWidth,
                    radius: 100,
                    fontSize: 14,
                    padding: singleButton
                        ? EdgeInsets.symmetric(horizontal: 24)
                        : null,
                    height: 40,
                    fontWeight: FontWeight.w600,
                    color: ColorsConfig.fff2f4f5,
                    onPressed: () {
                      RouterUtil.instance
                          .build()
                          .withBool('result', true)
                          .pop();
                    },
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
    return result?.getBool('result') ?? false;
  }

  ///显示对话框
  static Future<T?> showContentDialogV2<T>(
    BuildContext context, {
    required Widget content,
    bool showClose = false,
    bool canceledOutside = true,
  }) {
    final width = MediaQuery.of(context).size.width;
    return showDialog<T?>(
      context: context,
      builder: (_) {
        return WillPopScope(
          onWillPop: () => Future.value(canceledOutside),
          child: UnconstrainedBox(
            child: Dialog(
              insetPadding: EdgeInsets.zero,
              backgroundColor: Colors.transparent,
              elevation: 0,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Visibility(
                    visible: showClose,
                    child: Padding(
                      padding: EdgeInsets.only(bottom: 16),
                      child: IconButton(
                        icon: Icon(Icons.close),
                        onPressed: () {
                          RouterUtil.instance
                              .build()
                              .withBool('result', false)
                              .pop();
                        },
                      ),
                    ),
                  ),
                  Container(
                    width: width - 56,
                    margin: EdgeInsets.only(bottom: showClose ? 52 : 0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: content,
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
